package com.hotel.domain.service.impl;

import com.github.pagehelper.PageHelper;
import com.hotel.common.PageEntity;
import com.hotel.domain.dao.GuestsMapper;
import com.hotel.domain.dao.VipMapper;
import com.hotel.domain.service.GuestsService;
import com.hotel.pojo.Guests;
import com.hotel.pojo.Vip;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

@Service
public class GuestsServiceImpl implements GuestsService {

    @Autowired
    private GuestsMapper guestsMapper;
    @Autowired
    private VipMapper vipMapper;

    @Override
    @Transactional
    public int addGuests(Guests guests) {
        if(guests.getGuestIdcard() == null || "".equals(guests.getGuestIdcard())){
            return 0;
        }
        //查看该顾客是否存在
        Guests newGuest = new Guests();
        newGuest.setGuestIdcard(guests.getGuestIdcard());
        List<Guests> list = guestsMapper.getGuestsList(newGuest);
        if(list.size() != 0){
            guests.setGuestId(list.get(0).getGuestId());
            return 0;
        }else {
            return guestsMapper.addGuests(guests);
        }
    }

    @Override
    @Transactional
    public int updateGuests(Guests guests) {
        return guestsMapper.updateGuests(guests);
    }

    @Override
    public PageEntity<Guests> getGuestsList(Guests guests, int page, int perPage) {
        PageHelper.startPage(page, perPage);
        List<Guests> list = guestsMapper.getGuestsList(guests);
        int pageTotal = (int)Math.ceil(guestsMapper.getGuestsNum(guests)/(double)perPage);
        return new PageEntity<Guests>(list, page, pageTotal);
    }

    @Override
    @Transactional
    public int upToVip(int guestId) {
        //生成vip卡号
        DecimalFormat df = new DecimalFormat();
        df.applyPattern("00");
        String vipCard = new Date().getTime()/1000 + "" + df.format(guestId);
        Vip vip = new Vip();
        vip.setGuestId(guestId);
        vip.setVipCard(vipCard);
        return vipMapper.addVip(vip);
    }

}
